package com.mot.j2me.midlets;

/*
 * A free J2ME sample program to demonstrate
 * a SIMPLE LOGIN SCREEN TO LOGIN TO A HTTP SERVER 
 * FROM A J2ME phone
 *
 * @author William Alexander
 * code modified by @author Hitesh Ubharani
 * free for use as long as this comment is included in
 * in the program as it is
 * More Free Java programs available for download 
 * at http://www.java-samples.com
 *
 */
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

import java.io.*;

import javax.microedition.io.*;

public class Caching extends MIDlet implements CommandListener {

	TextField Pin = null;
	StringItem si;
	ChoiceGroup choiceMenu = new ChoiceGroup("Mlbs Demo", Choice.EXCLUSIVE);
	TextField Location = null;
	Form mainscreen, menu;
	TextBox t = null;
	StringBuffer b = new StringBuffer();
	Display myDisplay = null;
	private Command okCommand = new Command("OK", Command.OK, 1);
	private Command exitCommand = new Command("Exit", Command.EXIT, 0);
	private Command backCommand = new Command("Back", Command.BACK, 1);

	public Caching() {

		myDisplay = Display.getDisplay(this);
		choiceMenu.append("Disable Caching", null);
		choiceMenu.append("Enable Caching", null);
		menu = new Form("Mlbs Demo");
		menu.addCommand(exitCommand);
		menu.addCommand(okCommand);
		menu.append(choiceMenu);
		menu.setCommandListener(this);
		myDisplay.setCurrent(menu);
		mainscreen = new Form(" ");
		mainscreen.append("Loading....");
		si = new StringItem("", "");
		
	}

	public void startApp() throws MIDletStateChangeException {
	}

	public void pauseApp() {
	}

	protected void destroyApp(boolean unconditional)
			throws MIDletStateChangeException {
	}

	public void commandAction(Command c, Displayable d) {

		if ((c == okCommand)) {
			mainscreen.deleteAll();
			mainscreen.append(si);
			si.setText("Loading..");
			mainscreen.addCommand(backCommand);
			mainscreen.addCommand(exitCommand);
			mainscreen.setCommandListener(this);
			myDisplay.setCurrent(mainscreen);
			Ret ret = new Ret(this, choiceMenu.getSelectedIndex());
			ret.start();

		}

		if (c == backCommand) {
			//b = new StringBuffer();
				
			//si.setText(null);
			myDisplay.setCurrent(menu);
		}

		if (c == exitCommand) {
			try {
				destroyApp(true);
				notifyDestroyed();
			} catch (MIDletStateChangeException e) {
				e.printStackTrace();
			}

		}
	}

	public void displayString(String string) {
		// form.append(si);
		si.setText(string);

	}
}

class Ret extends Thread {

	private Caching midlet;
	String caching = "enable";
	private int selectedIndex;

	public Ret(Caching cache, int selectedIndex) {

		/**
		 * Constructor
		 * 
		 * EFFECTS: Initialise the server and store midlet information
		 * 
		 * @param midlet
		 *            The main application midlet
		 * @param server
		 *            Forecast Server URL
		 */

		this.midlet = cache;
		this.selectedIndex = selectedIndex;

	}

	public void run() {
		/**
		 * Entry point of the thread EFFECTS: call to connect() method
		 */

		try {

			loadPage(selectedIndex);

		} catch (Exception ex) {
			ex.printStackTrace();

		}

	}

	public void loadPage(int selectedIndex) {
		long endTime, startTime = System.currentTimeMillis();
		long time;
		String caching;
		if(selectedIndex == 0){
			caching = "disable";
		}
		else{
			caching = "enable";
		}
		String param1 = "query=testCache";
		param1+="&cache="+caching;
		param1+="&IMEI=0123456789";
		param1+="&appId=1";
		String str = loadURL(param1);
		// t = new TextBox("Reply",b.toString(),1024,0);
		midlet.b.setLength(0);
		str = strParser(str);
		System.out.println("After formatting : "+str);
		midlet.b.append(str);
		
		/// instead of apending here I'll call the string parser function which does the rendering
		
		midlet.mainscreen.append(midlet.b.toString());
		
		
		///
		
		endTime = System.currentTimeMillis();
		time = endTime - startTime;
		midlet.displayString("Load time is " + Long.toString(time) + "ms");
		midlet.myDisplay.setCurrent(midlet.mainscreen);
	}

	public String loadURL(String query){
		String URL   = "http://mlbs.no-ip.org:8080/MLBSWebApp/MlbsServlet"+"?"+query;
    	URL = urlEncoder(URL);
    	System.out.println("URL:"+URL);
    	
    
		HttpConnection c = null;
		InputStream is = null;
		try {
		  System.out.println("In XXXX .....\n\n");
		  c = (HttpConnection)Connector.open(URL);	
		  c.setRequestMethod(HttpConnection.GET);
		  is = c.openInputStream();
		  
		  ///////////
		  if (c.getResponseCode() == HttpConnection.HTTP_OK)
		  {
		        int length = (int) c.getLength();
		        String str;
		        if (length != -1){
		          byte servletData[] = new byte[length];
		          is.read(servletData);
		          str = new String(servletData);
		          System.out.println("server response:"+str);
		          return str;
		        }else  // Length not available...
		        {
		          ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
		          
		          int ch;
		          while ((ch = is.read()) != -1){
		            bStrm.write(ch);
		          }
		          str = new String(bStrm.toByteArray());
		          bStrm.close();
		        }
		        System.out.println("server response2:"+str);
		        return str;
		   
		  }
		  //////////
		}catch (Exception e) {
			// TODO: handle exception
		}finally {
			          try {
						is.close();
						c.close();
					} catch (Exception e) {
						
					}
			  }
		return null;
		} 
	
 	public static String urlEncoder(String s) {
 		if (s == null)
 			return s;
 		s=s.replace(' ' , '+');
 		return s;
 	}
 	
 	public static String strParser(String s){
 		if(s == null){
 			return null;
 		}
        s=s.replace(';', '\n');
        return s;
 	}
}